<template>
  <div class="createPost-container">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="100px">
      <div class="createPost-main-container">

        <el-row>
          <el-col v-if="!readOnly" :span="12">
            <el-form-item v-if="!readOnly" label="年份" prop="years" style="margin-bottom: 30px;">
              <el-input-number v-model="postForm.beginYear" style="width:150px" :min="0" :max="100" /> —
              <el-input-number v-model="postForm.endYear" style="width:150px" :min="0" :max="100" />
            </el-form-item>
            <el-form-item v-else prop="text1" style="clear:both;margin: 20px;font-size:16px;line-height:200%">{{ postForm.beginYear }}—{{ postForm.endYear }}</el-form-item>
            <el-form-item v-if="!readOnly" label="祝福语1" prop="text1" style="margin-bottom: 30px;">
              <el-input v-model="postForm.text1" type="textarea" @change="textchange" />
            </el-form-item>
            <el-form-item v-else prop="text1" style="clear:both;margin: 20px;font-size:16px;line-height:200%" v-html="postForm.text1" />
            <el-form-item v-if="!readOnly" label="祝福语2" prop="text2" style="margin-bottom: 30px;">
              <el-input v-model="postForm.text2" type="textarea" @change="textchange" />
            </el-form-item>
            <el-form-item v-else prop="text2" style="clear:both;margin: 20px;font-size:16px;line-height:200%" v-html="postForm.text2" />
            <el-form-item v-if="!readOnly" label="祝福语3" prop="text3" style="margin-bottom: 30px;">
              <el-input v-model="postForm.text3" type="textarea" @change="textchange" />
            </el-form-item>
            <el-form-item v-else prop="text3" style="clear:both;margin: 20px;font-size:16px;line-height:200%" v-html="postForm.text3" />

            <el-form-item v-if="!readOnly" label="背景图片" style="clear:both">
              <el-upload
                class="avatar-uploader"
                :action="this.$http.defaults.baseURL+'api/gen/file/upload/'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="myHeaders"
                accept="image/jpeg,image/png,image/gif"
              >
                <img v-if="imageUrl" :src="this.$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(imageUrl)" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
            <el-form-item v-else label="背景图片" style="clear:both">
              <a v-if="imageUrl" :href="this.$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(imageUrl)" target="_blank"><img :src="this.$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(imageUrl)" class="avatar"></a>
            </el-form-item>

            <el-form-item v-if="!readOnly" style="margin-bottom: 30px;">
              <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <div class="phoneback">
              <img class="phoneimg" :src="this.$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(imageUrl)">
              <div class="phonetext1">
                Dear 春波<br>
                <span v-html="text1" />
                <div style="text-align:right">——盘天</div>
              </div>
              <div class="phonetext2" v-html="text2" />
              <div class="phonetext3" v-html="text3" />
            </div>
          </el-col>

        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>

const defaultForm = {
  beginYear: '',
  endYear: '',
  text1: '', // 文章内容
  text2: '', // 文章内容
  text3: '', // 文章内容
  files: [], // 文章图片
  id: null
}

export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Object,
      default: null
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      classOption: [],
      rules: {
        text1: [{ validator: validateRequire }],
        text2: [{ validator: validateRequire }],
        text3: [{ validator: validateRequire }]
      },
      tempRoute: {},
      text1: '',
      text2: '',
      text3: ''
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        console.log('timestamp:' + val)
        if (this.infoid) {
          this.postForm = this.infoid
          this.imageUrl = this.infoid.imageId
          this.textchange()
        } else {
          this.postForm = Object.assign({}, defaultForm)
          this.imageUrl = ''
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    const day = new Date()
    day.setTime(day.getTime())
    this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    textchange() {
      this.text1 = this.postForm.text1.split('\n').join('<br>')
      this.text2 = this.postForm.text2.split('\n').join('<br>')
      this.text3 = this.postForm.text3.split('\n').join('<br>')
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    getData(id) {
      this.postForm = id
      // this.infoLoading = true
      // if (id) {
      //   this.$http
      //     .get('/api/busDynamicCenter/getById?&id=' + id)
      //     .then(response => {
      //       this.infoLoading = false
      //       if (response.data.success === true) {
      //         this.postForm = response.data.result
      //         this.postForm.isTop = !!this.postForm.isTop
      //         this.imageUrl = response.data.result.coverImg
      //       } else {
      //         console.log('获取失败:' + response.data.message)
      //         this.$message({
      //           message: '获取失败:' + response.data.message,
      //           type: 'error'
      //         })
      //       }
      //     })
      //     .catch(error => {
      //       console.log(error)
      //       this.infoLoading = false
      //     })
      // } else {
      //   this.$nextTick(() => {
      //     this.infoLoading = false
      //     this.postForm = Object.assign({}, defaultForm)
      //     const day = new Date()
      //     day.setTime(day.getTime())
      //     this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
      //     // this.$refs.editor.setContent('')
      //     this.imageUrl = ''
      //   })
      // }
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (this.imageUrl && this.imageUrl !== '') {
            if (this.postForm.beginYear && this.postForm.endYear && this.postForm.beginYear > this.postForm.endYear) {
              this.$message({
                message: '开始年份不能大于结束年份',
                type: 'error'
              })
            } else {
              this.saveInfo()
            }
          } else {
            this.$message({
              message: '请上传图片',
              type: 'error'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    saveInfo() {
      const para = {
        text1: this.postForm.text1,
        text2: this.postForm.text2,
        text3: this.postForm.text3,
        beginYear: this.postForm.beginYear ? this.postForm.beginYear : 0,
        endYear: this.postForm.endYear ? this.postForm.endYear : 100,
        imageId: this.imageUrl,
        id: this.postForm.id
      }
      this.loading = true
      this.$http
        .post('/api/busYearRemindSetting/saveSetting', para)
        .then(response => {
          this.loading = false
          this.postForm.status = 'published'
          this.postForm = Object.assign({}, defaultForm)
          if (response.data.success === true) {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.$emit('dialogHide')
          } else {
            console.log('提交失败:' + response.data.message)
            this.$message({
              message: '提交失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function(error) {
          console.log(error)
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .phoneback{
    width:400px;
    height:700px;
    margin:0 20px;
    background-position: top center;
    background-repeat:no-repeat;
    background-image:url('../../../assets/phone.png');
    background-size:contain;
    position: relative;
  }
  .phoneimg{
    position:absolute;
    left: 51px;
    top: 85px;
    height: 530px;
    width: 298px;
  }
  .phonetext1{
    position:absolute;
    left: 65px;
    top: 185px;
    color: #000;
    font-size: 12px;
    line-height: 28px;
    width: 270px;
    padding:20px;
    border-radius: 15px;
    background-image:url('../../../assets/alp35.png');
  }
  .phonetext1b{
    position:absolute;
    left: 85px;
    top: 320px;
    color: #000;
    font-size: 12px;
    line-height: 28px;
    width: 230px;
    text-align: right;
  }
  .phonetext2{
    position:absolute;
    left: 80px;
    top: 402px;
    color:#000;
    font-size:12px;
    line-height: 16px;
    width: 245px;
  }
  .phonetext3{
    position:absolute;
    left: 80px;
    top: 426px;
    color:#000;
    font-size: 12px;
    line-height: 28px;
    width: 245px;
  }
</style>
